<script setup>
import { Modal } from 'ant-design-vue'
import { CaretDownFilled, CheckCircleOutlined, ColumnHeightOutlined, DeleteOutlined, DoubleRightOutlined, DownOutlined, EditOutlined, KeyOutlined, LockOutlined, PlusOutlined, ReloadOutlined, SearchOutlined, SettingOutlined, UndoOutlined, UnlockOutlined, UpOutlined } from '@ant-design/icons-vue'
import { addUser, allocateRole, deleteUser, getUserList, getUserRole, getUserRoleList, resetPwd, unlockUser, updateUser } from '~@/api/system/index'

defineOptions({
  name: 'User',
})
// 新增用户
const userForm = ref()
const userTitle = shallowRef('')
const userOpen = ref(false)
const allocateOpen = ref(false)
const allocateLoading = ref(false)
const rules = computed(() => {
  return {
    userName: [
      { required: true, message: '请输入登录名', trigger: 'change' },
    ],
    realName: [
      { required: true, message: '请输入用户名称', trigger: 'change' },
    ],

  }
})
const formState = reactive({
  userId: null,
  userName: '',
  realName: '',
  sex: null,
  phone: '',
  email: '',
  status: 'ACTIVE',
})
const allocateInfo = reactive({
  userName: '',
  realName: '',
})

const message = useMessage()
const selectedRowKeys = shallowRef([])
const roleData = shallowRef([])
const columns = shallowRef([
  {
    title: '用户名称',
    dataIndex: 'realName',
  },
  {
    title: '登录名',
    dataIndex: 'userName',
  },

  {
    title: '状态',
    dataIndex: 'status',
    align: 'center',

  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    align: 'center',

  },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'left',
    fixed: 'right',
    width: '220px',

  },
])
const allocateColumns = shallowRef([
  {
    title: '角色编号',
    dataIndex: 'roleId',
  },
  {
    title: '角色名称',
    dataIndex: 'roleName',
  },
  {
    title: '角色类型',
    dataIndex: 'roleType',
  },

])
const loading = shallowRef(false)
const totalNum = shallowRef(0)
const pagination = reactive({
  pageSize: 8,
  pageSizeOptions: ['10', '20', '30', '40'],
  current: 1,
  total: totalNum,
  showSizeChanger: true,
  // showQuickJumper: true,
  showTotal: total => `总共：${total}`,
  onChange(current, pageSize) {
    pagination.pageSize = pageSize
    pagination.current = current
    init()
  },
})
const dataSource = shallowRef([])
const formModel = reactive({
  name: void 0,
})
const tableSize = ref(['large'])
const open = ref(false)
const options = computed(() => {
  return columns.value.map((item) => {
    if (item.dataIndex === 'action') {
      return {
        label: item.title,
        value: item.dataIndex,
        disabled: true,
      }
    }
    return {
      label: item.title,
      value: item.dataIndex,
    }
  })
})
const dropdownVisible = ref(false)
const getCheckList = computed(() => columns.value.map(item => item.dataIndex))
const state = reactive({
  indeterminate: false,
  checkAll: true,
  checkList: getCheckList.value,
})
onMounted(() => {
  init()
  // getType();
  // getChannel();
})
// 处理状态
function handleStatus(text) {
  switch (text) {
    case 'ACTIVE':
      return '正常'
    case 'INACTIVE':
      return '停用'
    default:
      return '锁定'
  }
}

async function init() {
  if (loading.value)
    return
  loading.value = true
  try {
    const { data } = await getUserList({
      param: { ...formModel },
      page: {
        currentPage: pagination.current,
        pageSize: pagination.pageSize,
      },

    })

    dataSource.value = data.data ?? []
    // dataSource.value = data.data ?? []
    totalNum.value = data.pageInfo.total
  }
  catch (e) {
    console.log(e)
  }
  finally {
    loading.value = false
  }
}
async function onSearch() {
  pagination.current = 1
  await init()
}
async function onReset() {
  formModel.name = void 0
  formModel.desc = void 0
  await init()
}
// 重置密码
async function handleReset(record) {
  Modal.confirm({
    title: '确认操作',
    content: `确定要重置用户 ${record.realName} 的密码吗？`,
    okText: '确认',
    cancelText: '取消',
    onOk() {
      return new Promise((resolve, reject) => {
        const res = resetPwd(record.userId)
          .then((res) => {
            if (res.data.code === 'SUCCESS') {
              message.success('重置成功')
              init()
              resolve() // 关闭对话框
            }
            else {
              message.error('操作失败')
              reject() // 保持对话框打开
            }
          })
          .catch(() => {
            // message.error('操作失败')
            reject() // 保持对话框打开
          })
      })
    },
    onCancel() {
      console.log('取消操作')
    },
  })
}
// 解锁
async function handleUnLocked(record) {
  Modal.confirm({
    title: '确认操作',
    content: `确定要解锁用户 ${record.realName} 吗？`,
    okText: '确认',
    cancelText: '取消',
    onOk() {
      return new Promise((resolve, reject) => {
        const res = unlockUser(record.userId)
          .then((res) => {
            if (res.data.code === 'SUCCESS') {
              message.success('操作成功')
              init()
              resolve() // 关闭对话框
            }
            else {
              message.error('操作失败')
              reject() // 保持对话框打开
            }
          })
          .catch(() => {
            // message.error('操作失败')
            reject() // 保持对话框打开
          })
      })
    },
    onCancel() {
      console.log('取消操作')
    },
  })
}

// 删除用户
async function handleDelete(record) {
  Modal.confirm({
    title: '确认操作',
    content: `确定要删除用户 “ ${record.realName} ” 吗？`,
    okText: '确认',
    cancelText: '取消',
    onOk() {
      return new Promise((resolve, reject) => {
        const res = deleteUser(record.userId)
          .then((res) => {
            if (res.data.code === 'SUCCESS') {
              message.success('操作成功')
              init()
              resolve() // 关闭对话框
            }
            else {
              message.error('操作失败')
              reject() // 保持对话框打开
            }
          })
          .catch(() => {
            // message.error('操作失败')
            reject() // 保持对话框打开
          })
      })
    },
    onCancel() {
      console.log('取消操作')
    },
  })
}

// 分配角色
function handleAllocate(record) {
  selectedRowKeys.value = []
  allocateInfo.userName = record.userName
  allocateInfo.realName = record.realName
  allocateInfo.userId = record.userId
  getRole()
  // selectedRowKeys.value = [1, 2]
  getCurrentRole(record)
  allocateOpen.value = true
}
// 查询角色列表
async function getRole() {
  allocateLoading.value = true
  try {
    const { data } = await getUserRoleList({
      param: { ...formModel },
    })

    roleData.value = data ?? []
    allocateLoading.value = false
  }
  catch (e) {
    console.log(e)
  }
  finally {
    allocateLoading.value = false
  }
}
// 查询当前用户已分配角色
async function getCurrentRole(record) {
  try {
    const { data } = await getUserRole(record.userId)
    // selectedRowKeys.value = [1, 2]
    selectedRowKeys.value = data.roleIds
  }
  catch (e) {
    console.log(e)
  }
  finally {
    loading.value = false
  }
}
// 确认分配角色
async function handleConfirm() {
  try {
    const { data } = allocateRole({ roleIds: selectedRowKeys.value, userId: allocateInfo.userId })
    message.success('分配成功')
    init()
    allocateOpen.value = false
  }
  catch (error) {
    console.log(3333, error)
  }
  finally {
    loading.value = false
  }
}
function onSelectChange(value) {
  console.log('selectedRowKeys changed: ', value)
  selectedRowKeys.value = value
}
function handleReturn() {
  open.value = false
}
// 打开新增用户弹窗
function addUserModal() {
  if (userForm.value) {
    userForm.value.resetFields()
  }
  resetUser()
  userTitle.value = '新增用户'
  userOpen.value = true
}
// 重置用户信息
function resetUser() {
  formState.email = void 0
  formState.phone = void 0
  formState.realName = void 0
  formState.userName = void 0
  formState.sex = void 0
  formState.userId = void 0
  formState.status = 'ACTIVE'
}
// 确认新增用户
async function handleOk() {
  try {
    await userForm.value.validate()
    if (formState.userId) {
      const { data } = await updateUser(formState)
      if (data.code === 'SUCCESS') {
        userOpen.value = false
        message.success('保存成功')
        init()
      }
    }
    else {
      const { data } = await addUser(formState)
      if (data.code === 'SUCCESS') {
        userOpen.value = false
        message.success('新增成功')
        init()
      }
    }
  }
  catch (error) {
    // message.error('请检查表单填写是否正确')
  }
}
// 编辑用户
async function handleEdit(record) {
  userOpen.value = true
  formState.userId = record.userId
  formState.userName = record.userName
  formState.realName = record.realName
  formState.sex = record.sex
  formState.phone = record.phone
  formState.status = record.status
  formState.email = record.email
  userTitle.value = '编辑用户'
}
function handleSizeChange(e) {
  tableSize.value[0] = e.key
}
function filterAction(value) {
  return columns.value.filter((item) => {
    if (value.includes(item.dataIndex))
      return true

    return false
  })
}
const filterColumns = ref(filterAction(getCheckList.value))
function handleCheckAllChange(e) {
  Object.assign(state, {
    checkList: e.target.checked ? getCheckList.value : [],
    indeterminate: true,
  })
  filterColumns.value = e.target.checked ? filterAction(getCheckList.value) : filterColumns.value.filter(item => item.dataIndex === 'action')
}
watch(
  () => state.checkList,
  (val) => {
    state.indeterminate = !!val.length && val.length < getCheckList.value.length
    state.checkAll = val.length === getCheckList.value.length
  },
)
function handleResetChange() {
  state.checkList = getCheckList.value
  filterColumns.value = filterAction(getCheckList.value)
}
function handleCheckChange(value) {
  const filterValue = filterAction(value)
  filterColumns.value = filterValue
}
const expand = ref(false)
</script>

<template>
  <page-container>
    <a-card mb-4>
      <a-form :model="formModel" layout="inline">
        <a-form-item name="userName" label="用户名称">
          <a-input v-model:value="formModel.name" placeholder="用户名/登录名" allow-clear />
        </a-form-item>
        <a-form-item>
          <a-space flex justify-end w-full>
            <a-button type="primary" @click="onSearch">
              <SearchOutlined />查询
            </a-button>
            <a-button type="primary" class="ml-2" ghost @click="addUserModal">
              <PlusOutlined />新增
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <a-card>
      <a-table bordered :loading="loading" :columns="filterColumns" :scroll="{ x: 1000 }" :data-source="dataSource" :pagination="pagination">
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'balance'">
            <span :style="{ color: record.balance < 0 ? 'red' : 'black' }">{{ Number(record.balance).toFixed(2) }}</span>
          </template>

          <template v-else-if="column.dataIndex === 'status'">
            <!-- <a-switch v-model:checked="record.status" /> -->
            <a-tag
              :color="record.status === 'ACTIVE' ? 'geekblue' : (record.status === 'INACTIVE' ? 'red' : 'volcano')"
            >
              {{ handleStatus(record.status) }}
            </a-tag>
          </template>
          <template v-else-if="column.dataIndex === 'certNo'">
            {{ handleCertcard(record.certNo) }}
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <div class="action flex flex-start items-center">
              <a-button type="link" @click="handleEdit(record)">
                <EditOutlined />
              </a-button>
              <a-button type="link" @click="handleDelete(record)">
                <DeleteOutlined />
              </a-button>
              <a-button v-if="record.status === 'LOCKED'" type="link" @click="handleUnLocked(record)">
                <UnlockOutlined />解锁
              </a-button>

              <a-dropdown>
                <a class="ant-dropdown-link" style="margin-left: 6px;" @click.prevent>
                  <DoubleRightOutlined style="margin-right: 3px;" />更多
                </a>
                <template #overlay>
                  <a-menu>
                    <a-menu-item @click="handleReset(record)">
                      <a-button type="text">
                        <KeyOutlined />重置密码
                      </a-button>
                    </a-menu-item>
                    <a-menu-item>
                      <a-button type="text" @click="handleAllocate(record)">
                        <CheckCircleOutlined />分配角色
                      </a-button>
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </div>
          </template>
        </template>
      </a-table>
    </a-card>
    <!-- 新增用户 -->
    <a-modal v-model:open="userOpen" :mask-closable="false" width="700px" :title="userTitle" :body-style="{ paddingTop: '25px', paddingBottom: '30px' }" ok-text="保存" @ok="handleOk">
      <a-form
        ref="userForm"
        :model="formState"
        :rules="rules"
        name="basic"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
      >
        <a-row>
          <a-col :span="24">
            <a-form-item name="realName" label="用户名称">
              <a-input v-model:value="formState.realName" placeholder="请输入用户名称" allow-clear />
            </a-form-item>
            <a-form-item name="userName" label="登录名">
              <a-input v-model:value="formState.userName" placeholder="请输入登录名" allow-clear />
            </a-form-item>

            <a-form-item label="手机号码">
              <a-input v-model:value="formState.phone" placeholder="请输入手机号码" />
            </a-form-item>

            <a-form-item label="邮箱">
              <a-input v-model:value="formState.email" placeholder="请输入邮箱" />
            </a-form-item>
          </a-col>
        </a-row>
        <div>
          <a-form-item label="性别">
            <a-radio-group v-model:value="formState.sex">
              <a-radio :value="1">
                男
              </a-radio>
              <a-radio :value="0">
                女
              </a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="状态">
            <a-radio-group v-model:value="formState.status">
              <a-radio value="ACTIVE">
                正常
              </a-radio>
              <a-radio value="INACTIVE">
                停用
              </a-radio>
              <a-radio value="LOCKED">
                锁定
              </a-radio>
            </a-radio-group>
          </a-form-item>
        </div>
      </a-form>
    </a-modal>
    <!-- 分配角色 -->
    <a-modal v-model:open="allocateOpen" :mask-closable="false" width="850px" title="分配角色" :body-style="{ paddingTop: '25px', paddingBottom: '50px' }" ok-text="确定" @ok="handleConfirm">
      <div class="mb-5" style="font-size: 16px;">
        <span class="mr-10 ">用户昵称：<span class="font-600" style="color:#172b4d">{{ allocateInfo.realName }}</span></span>   登录账号：<span class="font-600" style="color:#172b4d">{{ allocateInfo.userName }}</span>
      </div>
      <a-table :pagination="false" row-key="roleId" :row-selection="{ selectedRowKeys, onChange: onSelectChange }" bordered :loading="allocateLoading" :columns="allocateColumns" :data-source="roleData" />
    </a-modal>
  </page-container>
</template>

  <style lang="less" scoped>
    :deep(.ant-btn){
       padding: 4px 8px;
    }
    .line{
      color:#1677ff;
    }
    .userTitle{
      color:gray;
      width: 100%;
      padding:5px 0;
      border-bottom:1px solid #f1eded;
      margin-bottom: 20px;
    }
    .red{
      color:red;
      /* color:#ff4d4f; */
    }
    .card-title{
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      flex: auto;
      color: rgba(0, 0, 0, 0.88);
      font-weight: 600;
      font-size: 16px;
      line-height: 1.5;
    }
  @media screen and (max-width: 1200px) and (min-width: 992px) {
    .activeCard {
      margin-bottom: 24px;
    }
    .members {
      margin-bottom: 0;
    }
    .extraContent {
      margin-left: -44px;
      .statItem {
        padding: 0 16px;
      }
    }
  }

  @media screen and (max-width: 992px) {
    .activeCard {
      margin-bottom: 24px;
    }
    .members {
      margin-bottom: 0;
    }
    .extraContent {
      float: none;
      margin-right: 0;
      .statItem {
        padding: 0 16px;
        text-align: left;
        &::after {
          display: none;
        }
      }
    }
  }

  @media screen and (max-width: 768px) {
    .extraContent {
      margin-left: -16px;
    }
    .projectList {
      .projectGrid {
        width: 50%;
      }
    }
  }

  @media screen and (max-width: 576px) {
    .pageHeaderContent {
      display: block;
      .content {
        margin-left: 0;
      }
    }
    .extraContent {
      .statItem {
        float: none;
      }
    }
  }

  @media screen and (max-width: 480px) {
    .projectList {
      .projectGrid {
        width: 100%;
      }
    }
  }
  </style>
